package com.ffs.template.table;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.ffs.template.jdbc.JdbcTemplate;
import com.ffs.template.util.StringUtil;

import javax.sql.DataSource;
import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * 数据库表解析
 *
 * @author ffs80
 */
public class TableAnalysis {

    private static final TableAnalysis INSTANCE = new TableAnalysis();

    private static JdbcTemplate jdbcTemplate;

    public static TableAnalysis getInstance() {
        return INSTANCE;
    }

    /**
     * jdbc连接初始化
     */
    private void jdbcInit() {
        Properties properties = new Properties();

        //InputStream config = this.getClass().getClassLoader().getResourceAsStream("config/dbConfig.properties");
        try {
            //使用外部配置文件
            File file = new File("config/dbConfig.properties");
            FileInputStream config = new FileInputStream(file);
            properties.load(config);
            DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
            jdbcTemplate = new JdbcTemplate(dataSource);
        } catch (Exception e) {
            System.out.println("数据库连接错误，请检查数据库配置文件！");
            e.printStackTrace();
        }
    }

    /**
     * 表查询
     */
    public Map<String, List<TableAttr>> dataLoad() {
        jdbcInit();

        Map<String, List<TableAttr>> tableMap = new HashMap<>();
        //查询所有表
        List<String> tables = jdbcTemplate.queryList("show tables;", rs -> rs.getString(1));

        tables.forEach(p -> {
            List<TableAttr> tableAttrList = jdbcTemplate.queryList("SELECT COLUMN_NAME,DATA_TYPE,COLUMN_COMMENT FROM information_schema.`COLUMNS` WHERE TABLE_NAME = '" + p + "';", rs -> {
                TableAttr tableAttr = new TableAttr();
                tableAttr.setName(StringUtil.switchField(rs.getString(1)));
                tableAttr.setType(StringUtil.typeSwitch(rs.getString(2)));
                tableAttr.setComment(StringUtil.switchField(rs.getString(3)));
                return tableAttr;
            });
            tableMap.put(StringUtil.switchTableName(p), tableAttrList);
        });
        return tableMap;
    }
}
